from mcp import ClientSession, StdioServerParameters, types
import asyncio
import os

# AnyUrl用于资源URL的类型校验
from pydantic import AnyUrl

from mcp.client.stdio import stdio_client


def print_call_result(tag: str, result: types.CallToolResult) -> None:
    readable_parts: list[str] = []
    if "content" in result:
        for block in result.content:
            if isinstance(block, types.TextContent):
                readable_parts.append(block.text)
        printable_text = (
            "|".join(readable_parts) if readable_parts else "<no text content>"
        )
        print(f"[{tag}] text=", printable_text)
    if result.prompts:
        for block in result.prompts:
            if isinstance(block, types.Prompt):
                readable_parts.append(block.name)
        printable_text = (
            "|".join(readable_parts) if readable_parts else "<no text content>"
        )
        print(f"[{tag}]=", printable_text)


def print_prompt_message(tag: str, prompt: types.GetPromptResult) -> None:
    lines: list[str] = []
    for msg in prompt.messages:
        role = msg.role
        content = msg.content
        if isinstance(content, types.TextContent):
            lines.append(f"{role}:{content.text}")
        else:
            lines.append(f"{role}:非文本内容 {type(content).__name__}")
    print(f"{tag}\n" + "\n".join(lines))


async def main() -> None:
    base_dir = os.path.dirname(os.path.abspath(__file__))
    server_path = os.path.join(base_dir, "server.py")
    server_params = StdioServerParameters(command="python", args=[server_path], env={})
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            prompts = await session.list_prompts()
            print_call_result("prompts", prompts)

            greet_prompt = await session.get_prompt(
                "greet_user", arguments={"name": "Alice", "style": "formal"}
            )
            print_prompt_message("greet_user", greet_prompt)

            debug_prompt = await session.get_prompt(
                "debug_assistant",
                arguments={
                    "error": "IndexError: list index out of range",
                },
            )
            print_prompt_message("debug_assistant", debug_prompt)


if __name__ == "__main__":
    asyncio.run(main())
